package com.huihui.activity.search;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.huihui.R;
import com.huihui.base.BaseActivity;
import com.huihui.bean.Goods;
import com.huihui.bean.HistoryBean;
import com.huihui.datamanager.AppManager;
import com.huihui.fragment.BaseFragment;
import com.huihui.fragment.GoodsSeachFragment;
import com.huihui.fragment.NewsSearchFragment;
import com.huihui.fragment.SmallVideoSearchFragment;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 搜索页面
 * 分为视频和文章两种类型
 */
public class SearchActivity extends BaseActivity {

    private LinearLayout articile_ll;
    private TextView content_type;
    private ImageView content_type_select;
    private EditText search;
    private TextView cancel;
    private ListView listview;
    private int type = 1;
    private int class_id = 0;
    private SmallVideoSearchFragment smallview_search;
    private GoodsSeachFragment goodsSeachFragment;
    private NewsSearchFragment news_search;
    private List<String> mHistoryList;
    private HistoryListAdapter mHistoryRecordAdapter;
    private FrameLayout contentLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initData();
        initView();
        initListener();
    }


    private void initView() {
        articile_ll = (LinearLayout) findViewById(R.id.articile_ll);
        content_type = (TextView) findViewById(R.id.content_type);
        content_type_select = (ImageView) findViewById(R.id.content_type_select);
        contentLayout = (FrameLayout) findViewById(R.id.search_content_layout);
        search = (EditText) findViewById(R.id.search);
        cancel = (TextView) findViewById(R.id.cancel);
        listview = (ListView) findViewById(R.id.listview);

        cancel.setVisibility(View.VISIBLE);
    }


    private void initData() {
        HistoryBean history = AppManager.getHistory();
        if (history == null) {
            //首次设置历史数据，防止get的时候空指针
            history = new HistoryBean();
            List<String> list = new ArrayList<>();
            history.setList(list);
            AppManager.setHistory(history);
        }
        mHistoryList = history.getList();
        //初始化历史数据
    }

    private void initListener() {
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInput(getContext());
                finish();
            }
        });
        //搜索类型选择监听
        articile_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showClassPop();
            }

        });
        /**文本输入框触摸监听 显示历史列表*/
        search.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                showHistoryList();
                return false;
            }
        });
        search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideInput(SearchActivity.this);
                }
            }
        });
        /**
         * 搜索 监听
         */
        search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//搜索按键action
                    hideInput(getContext());
                    String keyWord = v.getText().toString();
                    if (TextUtils.isEmpty(keyWord)) {
                        return true;
                    }
                    HistoryBean history = AppManager.getHistory();
                    if (history == null) {
                        history = new HistoryBean();
                        List<String> list = new ArrayList<>();
                        history.setList(list);
                    }
                    history.getList().add(keyWord);
                    AppManager.setHistory(history);
                    //隐藏历史列表 显示fragment Layout
                    hideHistoryList();
                    search(keyWord);
                    return true;
                }
                return false;
            }


        });

    }

    /**
     * 显示历史列表记录
     */
    private void showHistoryList() {
        listview.setVisibility(View.VISIBLE);
        contentLayout.setVisibility(View.GONE);
        //每次点击 重新获取历史
        HistoryBean history = AppManager.getHistory();
        mHistoryList = history.getList();
        if (mHistoryList == null) {
            return;
        }
        mHistoryRecordAdapter = new HistoryListAdapter(this, R.layout.activity_search_history_item, mHistoryList);
        listview.setAdapter(mHistoryRecordAdapter);
    }

    /**
     * 隐藏历史列表
     */
    private void hideHistoryList() {
        listview.setVisibility(View.GONE);
        contentLayout.setVisibility(View.VISIBLE);
    }

    /**
     * 显示类型列表   并设置搜索类型
     */
    private void showClassPop() {
        View view = LayoutInflater.from(this).inflate(R.layout.class_pop_layout, null);
        final PopupWindow classPop = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        classPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        classPop.setTouchable(true);
        classPop.setOutsideTouchable(true);
        classPop.showAsDropDown(articile_ll);
        articile_ll.setBackgroundResource(R.drawable.shape_cccccc_30px_f4f4f4_left2);
        classPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                articile_ll.setBackgroundResource(R.drawable.shape_cccccc_30px_f4f4f4_left);
            }
        });
        view.findViewById(R.id.class_goods).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                content_type.setText("商品");
                class_id = 0;
                classPop.dismiss();
            }
        });
        view.findViewById(R.id.class_video).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInput(getContext());
                content_type.setText("视频");
                type = 2;
                class_id = 1;
                classPop.dismiss();
            }
        });
        view.findViewById(R.id.class_articile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInput(getContext());
                content_type.setText("文章");
                type = 1;
                class_id = 2;
                classPop.dismiss();
            }
        });



    }

    @Override
    public void onBackPressed() {
        hideInput(getContext());
        super.onBackPressed();
    }

    /**
     * 历史列表适配器
     */
    public class HistoryListAdapter extends CommonAdapter<String> {
        private List<String> mList;

        private HistoryListAdapter(Context context, int layoutId, List<String> datas) {
            super(context, layoutId, datas);
            this.mList = datas;
            this.mContext = context;
        }

        @Override
        protected void convert(ViewHolder viewHolder, final String item, final int position) {
            final TextView historyName = viewHolder.getView(R.id.history_item_name);
            historyName.setText(item);
            ImageView deleteView = viewHolder.getView(R.id.history_delete);
            historyName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //搜索
                    hideHistoryList();
                    search(item);

                }
            });
            deleteView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mList.remove(position);
                    HistoryBean historyBean = AppManager.getHistory();
                    historyBean.setList(mList);
                    AppManager.setHistory(historyBean);
                    mHistoryRecordAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    /**
     * 根据类型进行搜索
     *
     * @param keyWord 关键词
     */
    private void search(String keyWord) {
        hideInput(getContext());
        if(class_id == 0){
            searchGoods(keyWord);
        }else  if (class_id == 1) {
            seatchVideo(keyWord);
        } else if (class_id == 2) {
            searchNew(keyWord);
        }
    }
    private void searchGoods(String keyWord){
        initGoodsFragment();
        switchFragment(goodsSeachFragment);
        goodsSeachFragment.setKeyWord(keyWord);
    }
    /**
     * 显示视频fragment
     */
    private void seatchVideo(String keyWord) {
        initSmallFragment();
        switchFragment(smallview_search);
        smallview_search.setKeyWords(keyWord);
    }

    /**
     * 显示文章fragment
     */
    private void searchNew(String keyWord) {
        initNewsSearchFragment();
        switchFragment(news_search);
        news_search.setKeyWords(keyWord);
    }

    private void initNewsSearchFragment() {

        if (news_search == null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            news_search = new NewsSearchFragment();
            fragmentTransaction.add(R.id.search_content_layout, news_search);
            fragmentTransaction.commit();
        }
    }

    private void initSmallFragment() {
        if (smallview_search == null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            smallview_search = new SmallVideoSearchFragment();
            fragmentTransaction.add(R.id.search_content_layout, smallview_search);
            fragmentTransaction.commit();
        }
    }

    private void initGoodsFragment() {
        if (goodsSeachFragment == null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            goodsSeachFragment = new GoodsSeachFragment();
            fragmentTransaction.add(R.id.search_content_layout, goodsSeachFragment);
            fragmentTransaction.commit();
        }
    }


    /**
     * 切换fragment
     *
     * @param fragment
     */
    private void switchFragment(BaseFragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragment(fragmentTransaction);
        fragmentTransaction.show(fragment);
        fragmentTransaction.commit();
    }

    /**
     * 隐藏错有fragment
     */
    private void hideFragment(FragmentTransaction fragmentTransaction) {
        if (news_search != null) {
            fragmentTransaction.hide(news_search);
        }
        if (smallview_search != null) {
            fragmentTransaction.hide(smallview_search);
        }
        if(goodsSeachFragment != null){
            fragmentTransaction.hide(goodsSeachFragment);
        }
    }
}
